package com.asset.salesforce.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.model.Account;
import com.asset.salesforce.model.BasicView;
import com.asset.salesforce.model.BasicViewList;
import com.asset.salesforce.model.Employee;
import com.asset.salesforce.model.Lead;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.SearchService;

@Controller
public class SearchController {

	@Autowired
	private SearchService searchService ;
	
	@Autowired
	private EmployeeService employeeService;
	
	@RequestMapping(value="/searchBoth/{empId}/query={query}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public BasicViewList searchAccountsAndLeads(@PathVariable String empId,@PathVariable String query) {

		Employee userDetails = employeeService.getById(Integer.parseInt(empId));
		List<Lead>leads = new ArrayList<Lead>();
		 leads =searchService.searchLead(query);
		 List<Account>  accounts = new ArrayList<Account>();
		 accounts = searchService.searchAccount(query);
		List<BasicView>basicViews = new ArrayList<BasicView>();
		if( leads != null){
			for(Lead lead : leads){
				if(lead.getLeadOwner().getCompany().getId().equals(userDetails.getCompany().getId()) && !lead.getIsDeleted()){
					BasicView basicView = new BasicView(null, lead);
					basicViews.add(basicView);
				}
			}
			
		}
		if( accounts != null){
			for(Account account : accounts){
				if(account.getAccountCreator().getCompany().getId().equals(userDetails.getCompany().getId()) && !account.getIsDeleted()){
					BasicView basicView = new BasicView(account, null);
					basicViews.add(basicView);
				}
			}
			
		}
		BasicViewList basicViewList = new BasicViewList();
		basicViewList.setBasicViews(basicViews);
		return basicViewList;
	}
}
